package com.freedom.yefeng.yfrecyclerview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

import com.freedom.yefeng.yfrecyclerview.util.LogUtil;

/**
 * Created by yefeng on 8/7/15.
 * github:yefengfreedom
 * this is a list view base on recycler view,with auto load more model,divider
 */
public class YfListRecyclerView extends RecyclerView {

    public static final int WRAP_CONTENT = -1;

    private static final String TAG = "YfListView";

    private LinearLayoutManager mLayoutManager;
    private Adapter mAdapter;
    private //用来标记是否正在向最后一个滑动
            boolean isSlidingToLast = false;

    public YfListRecyclerView(Context context) {
        super(context);
    }

    public YfListRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public YfListRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    /**
     * set list divider
     *
     * @param dividerRes divider resource
     */
    public void setDivider(int dividerRes) {
        setDivider(dividerRes, WRAP_CONTENT);
    }

    /**
     * set list divider
     *
     * @param dividerRes    divider resource
     * @param dividerHeight divider height
     */
    public void setDivider(int dividerRes, int dividerHeight) {
        Drawable drawable = getResources().getDrawable(dividerRes);
        setDivider(drawable, dividerHeight);
    }

    /**
     * set list divider
     *
     * @param drawable      drawable
     * @param dividerHeight divider height
     */
    public void setDivider(final Drawable drawable, final int dividerHeight) {
        if (null == drawable) {
            throw new NullPointerException("drawable resource is null");
        }
        addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
                int left = parent.getPaddingLeft();
                int right = parent.getWidth() - parent.getPaddingRight();

                int childCount = parent.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    View child = parent.getChildAt(i);

                    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                    int top = child.getBottom() + params.bottomMargin;
                    int bottom;
                    if (dividerHeight == WRAP_CONTENT) {
                        bottom = top + drawable.getIntrinsicHeight();
                    } else {
                        if (dividerHeight < 0) {
                            bottom = top;
                        } else {
                            bottom = top + dividerHeight;
                        }

                    }

                    drawable.setBounds(left, top, right, bottom);
                    drawable.draw(c);
                }
            }
        });
    }

    /**
     * set list divider
     *
     * @param drawable drawable
     */
    public void setDivider(Drawable drawable) {
        setDivider(drawable, WRAP_CONTENT);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        this.mAdapter = adapter;
        super.setAdapter(this.mAdapter);
    }

    @Override
    public void setLayoutManager(LayoutManager layout) {
        this.mLayoutManager = (LinearLayoutManager) layout;
        super.setLayoutManager(this.mLayoutManager);
    }

    /**
     * enable list view auto load more
     *
     * @param loadMoreListener load more listener
     */
    public void enableAutoLoadMore(final YfLoadMoreListener loadMoreListener) {


        addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (null == mLayoutManager || null == mAdapter) {
                    return;
                }
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if (dy > 0) {
                    //大于0表示正在向下滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0表示停止或向上滚动
                    isSlidingToLast = false;
                }

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LogUtil.e(TAG,"scrollStateChanged");

                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {

                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = mLayoutManager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = mLayoutManager.getItemCount();
                    LogUtil.i(TAG, "lastVisibleItem = " + lastVisibleItem +" ; totalItemCount = "
                            +totalItemCount +" ; isSlidingToLast = "+isSlidingToLast  );
                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                        if (null != loadMoreListener) {
                            LogUtil.d(TAG, "loadMore");
                            loadMoreListener.loadMore();
                        }
                    }
                }

            }

        });
    }
}
